package example.fileupload;

import com.google.protobuf.ByteString;
import grpc.htsoft.fileupload.*;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;


import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class fileclient2 {
    public static void main(String[] argc) throws IOException {
        System.out.println("Hello, FileClient2!");

        GRPCServer SERVER = new GRPCServer();
       Executor EXECUTOR = Executors.newSingleThreadExecutor();

        EXECUTOR.execute(SERVER::start);
         FileServiceGrpc.FileServiceStub fileServiceStub;
        var channel = ManagedChannelBuilder.forAddress("localhost", 50096)
                .usePlaintext()
                .build();
        fileServiceStub = FileServiceGrpc.newStub(channel);

        var latch = new CountDownLatch(1);
        StreamObserver<FileUploadRequest> streamObserver = fileServiceStub.upload(new FileUploadObserver());

        // input file for testing
        Path path = Paths.get("/Users/zgw/Pictures/vlcsnap-2020-07-29-10h36m29s719.png");

        // build metadata
        FileUploadRequest metadata = FileUploadRequest.newBuilder()
                .setMetadata(MetaData.newBuilder()
                        .setName("output1")
                        .setType("png").build())
                .build();
        streamObserver.onNext(metadata);

        // upload bytes
        InputStream inputStream = Files.newInputStream(path);
        byte[] bytes = new byte[4096];
        int size;
        while ((size = inputStream.read(bytes)) > 0){
            FileUploadRequest uploadRequest = FileUploadRequest.newBuilder()
                    .setFile(File.newBuilder().setContent(ByteString.copyFrom(bytes, 0 , size)).build())
                    .build();
            streamObserver.onNext(uploadRequest);
        }
        // close the stream
        inputStream.close();
        streamObserver.onCompleted();



    }
//
//
//    private static class FileUploadObserver implements StreamObserver<FileUploadResponse> {
//
//        private final CountDownLatch latch;
//        public FileUploadObserver(CountDownLatch latch) {
//            this.latch = latch;
//        }
//
//        @Override
//        public void onNext(FileUploadResponse fileUploadResponse) {
//            System.out.println(
//                    "File upload status :: " + fileUploadResponse.getStatus()
//            );
//        }
//
//        @Override
//        public void onError(Throwable throwable) {
//            throwable.printStackTrace();
//        }
//
//        @Override
//        public void onCompleted() {
//            System.out.println("Done");
//            this.latch.countDown();
//        }
//    }
}
